import 'dart:async';
import 'dart:math';

import 'package:ds18LedBtc/search/search.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';
import 'package:flutter_sound/flutter_sound.dart';

import '../bluetooth/blue_data_model.dart';
import '../bluetooth/send_data.dart';
import '../tool/assets.dart';
import 'color_view.dart';

class MyHome extends StatefulWidget {
  const MyHome({super.key});

  @override
  State<MyHome> createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {
  int _currentIndex = 0;
  List<DataModel> device_data_list = [];
  List<bool> btn_status = [false, false, false];
  String _bright = '5';
  final List<String> _bottomImgs = [assets.turn_off, assets.mic, assets.settings];
  FlutterSoundRecorder _audioRecorder = FlutterSoundRecorder();
  StreamController<Uint8List> _audioStreamController = StreamController<Uint8List>();

  @override
  void initState() {
    super.initState();
    listen();
    getBright();
    listenBluetooth(context);
  }

  @override
  void dispose() {
    super.dispose();
  }

  int code(int value) => (value * (_bright).float / 10.0).round();
  int decode(int value) => min(255, (value * 10.0 / (_bright).float).round());

  ///方法
  void method(String tag, dynamic value) {
    switch (tag) {
      case 'Speed':
      case 'LEDType':
        for (var model in device_data_list) {
          if (tag == 'LEDType') {
            model.type = value as int;
          } else if (tag == 'Speed') {
            model.speed = value as int;
          }
          SendData.send('指定颜色模式', model);
        }

        ///关闭mic状态
        setState(() => btn_status[1] = false);
        stopRecorder();
      case 'Color':
      case 'Bright':
        var map = value as Map<String, int>;
        List<int> list = (map['Color'] as int).bytes;

        ///这里非常重要
        ///因为当第一个元素是 0，时，，调用.bytes，会丢掉第一个0的值
        ///比如[0x00,0x01,0x02]，转换成10进制=258，可是258反过来转换成[int]，却=[0x01,0x02]，所以要自动补齐左边的
        list = list.length == 2 ? list.padLeft(3) : list;
        int bright = (map['Bright'] as int);
        _bright = '$bright';
        saveBright(_bright);
        for (var model in device_data_list) {
          int red = list.isEmpty ? model.red : list[0];
          int green = list.isEmpty ? model.green : list[1];
          int blue = list.isEmpty ? model.blue : list[2];
          print('==============>   rgb = ${red},${green},${blue}');

          model.red = code(red);
          model.green = code(green);
          model.blue = code(blue);
          SendData.send('单色模式', [model.red, model.green, model.blue]);
        }
      default:
    }
  }

  Widget _btn(String icon, Function() onTap) {
    return IconButton(
        padding: const EdgeInsets.all(3),
        highlightColor: Colors.white.withOpacity(0.1),
        onPressed: onTap,
        icon: Image.asset(icon, fit: BoxFit.fill));
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕的宽度
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;

    // 设置状态栏背景颜色和图标颜色
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏背景色
      statusBarIconBrightness: Brightness.light, // 状态栏图标颜色 (白色图标)
    ));

    return Scaffold(
        appBar: null,
        resizeToAvoidBottomInset: false, // 确保键盘弹出时，页面不自动调整大小
        body: SizedBox(
          width: screenWidth,
          height: screenHeight,
          child: Stack(
            children: [
              ///上半部分背景
              Positioned(
                  left: 0,
                  right: 0,
                  top: 0,
                  height: screenHeight / 2.0,
                  child: Image.asset(assets.bg_color_top, fit: BoxFit.fill)),

              ///下半部分背景
              Positioned(
                  left: 0,
                  right: 0,
                  top: screenHeight / 2.0,
                  bottom: 0,
                  child: Image.asset(assets.bg_color_bottom, fit: BoxFit.fill)),

              ///body
              Positioned(
                  child: Column(
                children: [
                  ///ColorView
                  Expanded(
                      child: ColorView(
                          currentType: device_data_list.isEmpty ? 1 : device_data_list.last.type,
                          currentBright: (_bright).float,
                          currentSpeed: device_data_list.isEmpty ? 1 : device_data_list.last.speed.toDouble(),
                          selectColor: device_data_list.isEmpty
                              ? 0
                              : (decode(device_data_list.last.red) << 16) |
                                  (decode(device_data_list.last.green) << 8) |
                                  decode(device_data_list.last.blue),
                          onChanged: method)),

                  ///bottombar
                  BottomNavigationBar(
                    currentIndex: _currentIndex,
                    onTap: (index) {
                      setState(() => _currentIndex = index);
                      if (index == 0) {
                        btn_status[index] = !btn_status[index];
                        btn_status[1] = btn_status[index] ? btn_status[1] : false;
                        for (var model in device_data_list) {
                          model.isOn = btn_status[index];
                          SendData.send('开关', btn_status[index]);
                        }
                      } else if (index == 1) {
                        if (btn_status[2] == false) {
                          return;
                        }
                        btn_status[index] = !btn_status[index];
                        // SendData.send('麦克风', btn_status[index]);
                        prepareOpenMic(context, btn_status[index]);
                      } else if (index == 2) {
                        Navigator.of(context).push(MaterialPageRoute(builder: (context) => const SearchView()));
                      }
                    },
                    type: BottomNavigationBarType.fixed,
                    backgroundColor: Color_bg_view,
                    selectedItemColor: Colors.red,
                    items: _bottomImgs.asMap().entries.map(($0) {
                      return BottomNavigationBarItem(
                          icon: Padding(
                              padding: const EdgeInsets.only(top: 0),
                              child: SizedBox(
                                width: 30,
                                height: 30,
                                child: Stack(
                                  children: [
                                    Positioned(child: Image.asset($0.value, width: 30, height: 30)),
                                    Center(
                                        child: ColorFiltered(
                                      colorFilter: ColorFilter.mode(
                                        btn_status[$0.key] ? Color_btn_hight : Colors.white, // 使用你指定的颜色
                                        BlendMode.srcIn, // 只改变不透明的部分
                                      ),
                                      child: Image.asset($0.value),
                                    ))
                                  ],
                                ),
                              )),
                          label: '');
                    }).toList(),
                  ),
                ],
              )),
            ],
          ),
        ));
  }
}

///蓝牙的一些监听
extension _MyHomeStateExtesion on _MyHomeState {
  void listenBluetooth(BuildContext context) {
    ///监听蓝牙外设连接状态
    BluetoothManager.instance.connectionStateStream.listen((value) {
      var state = value.values.first;
      switch (state) {
        case BluetoothConnectionState.connected:
          EasyLoading.showSuccess('Connect successfully');
          listen();
          SendData.send('查询数据', '');
        case BluetoothConnectionState.disconnected:
          setState(() => btn_status[2] = false);
          EasyLoading.showSuccess('disConnected!', duration: const Duration(milliseconds: 1500));
        case BluetoothConnectionState.connecting:
          break;
        case BluetoothConnectionState.disconnecting:
          print('设备断开连接中');
          break;
      }
    });

    ///监听蓝牙广播状态
    BluetoothManager.instance.bluetoothStateStream.listen((state) {
      switch (state) {
        case BluetoothAdapterState.on:
          break;
        case BluetoothAdapterState.off:
          EasyLoading.showInfo('Bluetooth turned off');
        default:
      }
    }, onError: (error) {
      EasyLoading.showInfo('${error.message}');
    });
  }

  void listen() {
    ///监听数据回调
    BluetoothManager.instance.read(
        service_uuid: read_service,
        characteristics_uuid: read_uuid,
        onResponse: (data) {
          print('收到蓝牙上传的数据是 == ${data.toHexstr(' |')}');
          if (data.length >= 12 && data[0] == 0x66) {
            btn_status[0] = data[2] == 0x23;

            ///设备开关状态
            btn_status[2] = true;
            DataModel model = DataModel(
                name: data[1].bytes.toHexstr(),
                isOn: data[2] == 0x23,
                type: data[3],
                isPlay: data[4] == 0x20,
                speed: 32 - data[5],
                red: decode(data[6]),
                green: decode(data[7]),
                blue: decode(data[8]),
                warmWhite: data[9],
                version: data[10]);
            GlobalDataNotifier().updateData(model);
            if (device_data_list.any(($0) => $0.name == model.name) == false) {
              setState(() => device_data_list.add(model));
            }
          }
        });
  }
}

///保存数据
extension _MyHomeStateExtesion2 on _MyHomeState {
  Future<void> saveBright(String groupName) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('bright', groupName);
  }

  Future<void> getBright() async {
    final prefs = await SharedPreferences.getInstance();
    _bright = prefs.getString('bright') ?? '5';
    setState(() {});
  }
}

///录音操作
extension _MyHomeStateExtesion3 on _MyHomeState {
  ///预请求，运行时请求 权限
  Future<void> prepareOpenMic(BuildContext context, bool isOpen) async {
    if (await Permission.microphone.request().isGranted) {
      // 权限已被授予，可以开始录音
      if (isOpen) {
        openRecorder();
        processAudioStream();
      } else {
        stopRecorder();

        ///关闭要恢复单色模式
        for (var model in device_data_list) {
          SendData.send('单色模式', [model.red, model.green, model.blue]);
        }
      }
      isOpen ? openRecorder() : stopRecorder();
    } else {
      showAlert(context, 'MIC requires recording permissions', ['OK'], (p1) {});
    }
  }

  ///打开mic录音
  void openRecorder() async {
    await _audioRecorder.openRecorder();
    _audioRecorder.startRecorder(codec: Codec.pcm16, toStream: _audioStreamController.sink);
  }

  ///关闭mic录音
  void stopRecorder() async {
    await _audioRecorder.stopRecorder();
    await _audioRecorder.closeRecorder();
  }

  ///接收到 录音收音数据流
  void processAudioStream() {
    // 假设referencePressure是参考声压
    double referencePressure = 20.0 * pow(10, -6);
    bool receive = true;
    _audioStreamController.stream.listen((data) {
      if (receive == false) {
        return;
      }
      receive = false;
      Future.delayed(const Duration(milliseconds: 200), () {
        receive = true;
      });

      double rms = calculateRMS(data); // 计算音频数据的RMS值
      double db = 20 * log(rms / referencePressure); // 转换为分贝
      // 如果音频分贝低于噪声阈值，认为是背景噪音，不进行处理
      // if (db < noiseThreshold) {
      //   print("背景噪音，忽略");
      //   return;
      // }

      controlLED(db); // 根据分贝值控制LED
    });
  }

  void controlLED(double db) {
    // 根据分贝值控制LED灯的逻辑
    // 这里需要实现具体的LED控制逻辑

    // 1. 限制 dB 范围，避免 dB 值过高或过低
    db = db.clamp(320, 420); // 限制 dB 在合理范围内

    // // 2. 计算 RGB 每个通道的值
    // int red, green, blue;

    // // 使用对数映射来调整 RGB 值，避免高 dB 值过于剧烈
    // red = logMapping(db, 330.0, 420.0, 0, 255); // 红色通道：高 dB 值时红色最强
    // green = logMapping(db, 330.0, 420.0, 0, 255); // 绿色通道：中等 dB 值时绿色最强
    // blue = logMapping(db, 330.0, 420.0, 0, 255); // 蓝色通道：低 dB 值时蓝色最强

    // 打印 RGB 调整结果，供调试使用
    // print('===============> 录入音频数据  ==== red = ${red} ， green = ${green}, blue = ${blue}');
    double s = max(0, db - 320) / 45;
    for (var model in device_data_list) {
      SendData.send('单色模式', [(model.red * s).toInt(), (model.green * s).toInt(), (model.blue * s).toInt()]);
    }

    // SendData.send('手机麦克风收音', [red, green, blue]);
    // 这里可以使用调整后的 RGB 值去控制 LED 或其他显示效果
    // controlLED(red, green, blue);  // 控制 LED
  }

  ///计算音频数据的RMS（Root Mean Square，均方根）
  double calculateRMS(List<int> data) {
    // 假设data是16位的PCM音频数据，每个样本占用2个字节
    int numSamples = data.length ~/ 2;
    double sumSquares = 0.0;

    for (int i = 0; i < data.length; i += 2) {
      // 将两个字节组合成一个16位的样本值（小端序）
      int sample = (data[i] & 0xFF) | ((data[i + 1] & 0xFF) << 8);
      // 将16位有符号整数转换为有符号的32位整数
      if (sample > 32767) {
        sample -= 65536;
      }
      // 计算平方并累加
      sumSquares += sample * sample;
    }

    // 计算平均值
    double meanSquare = sumSquares / numSamples;
    // 取平方根得到RMS值
    double rms = sqrt(meanSquare);
    return rms;
  }

  /// 使用对数映射 dB 到 RGB 范围
  int logMapping(double db, double minDb, double maxDb, int minColor, int maxColor) {
    // 如果 db 小于 minDb，返回最小值；如果 db 大于 maxDb，返回最大值
    if (db <= minDb) return minColor;
    if (db >= maxDb) return maxColor;

    // 对数映射公式：log10(dB) 映射到 [minColor, maxColor] 区间
    double logDb = log(db) / log(10); // 转换 dB 为对数值，log10(dB)
    double logMinDb = log(minDb) / log(10); // 转换 minDb 为对数值
    double logMaxDb = log(maxDb) / log(10); // 转换 maxDb 为对数值

    // 对数插值计算：通过对数比例计算 RGB 值
    double scale = (logDb - logMinDb) / (logMaxDb - logMinDb);

    // 根据 scale 返回计算出来的 RGB 值
    return ((scale * (maxColor - minColor) + minColor).toInt()).clamp(minColor, maxColor);
  }
}
